class WebSocketClient {
  constructor() {
    this.ws = null;
    this.reconnectTimer = null;
    this.reconnectCount = 0;
    this.maxReconnectCount = 5;
    this.messageHandlers = new Set();
    this.lastToken = null;
    this.lastSiteId = null;
    this.heartbeatTimer = null;
    this.heartbeatInterval = 30000; // 30秒发送一次心跳
    this.lastHeartbeatTime = null;
    this.heartbeatTimeout = 60000; // 60秒无响应则重连
    this.isConnecting = false;
  }

  connect(token, siteId) {
    if (this.isConnecting) {
      console.log('WebSocket is already connecting, skipping...');
      return;
    }
  
    if (this.ws && this.ws.readyState === WebSocket.OPEN) {
      console.log('WebSocket already connected');
      return;
    }
  
    this.isConnecting = true;
  
    // 保存连接参数
    this.lastToken = token;
    this.lastSiteId = siteId;
  
    // 从token中获取用户ID
    let userId = this.getUserIdFromToken(token);
    if (!userId) {
      console.error('无法从token中获取用户ID');
      this.isConnecting = false;
      return;
    }
  
    // 如果传入了siteId，则将userId设置为siteId
    if (siteId) {
      userId = siteId;
      console.log(`使用siteId作为userId: ${userId}`);
    }

    // 构建WebSocket URL，确保包含所有必要参数
    const params = new URLSearchParams();
    params.append('userId', userId);
    if (siteId) {
      params.append('siteId', siteId);
    }
    params.append('token', token); // 添加token参数

    const wsUrl = `ws://192.168.40.38:8080/zsd-order/ws?${params.toString()}`;
    console.log('Connecting to WebSocket:', wsUrl);
    
    try {
      this.ws = new WebSocket(wsUrl);

      // 在连接建立后立即发送认证消息
      this.ws.onopen = () => {
        console.log('WebSocket连接成功');
        this.isConnecting = false;
        this.reconnectCount = 0;
        this.lastHeartbeatTime = Date.now();

        // 发送认证消息
        const authMessage = {
          type: 'auth',
          userId: userId,
          siteId: siteId,
          token: token
        };
        this.ws.send(JSON.stringify(authMessage));
        console.log('Sent auth message:', authMessage);

        // 连接成功后等待一段时间再开始发送心跳
        setTimeout(() => {
          this.startHeartbeat();
        }, 5000);
      };

      this.ws.onmessage = (event) => {
        try {
          let message;
          // 尝试解析JSON
          try {
            message = JSON.parse(event.data);
          } catch (e) {
            // 如果不是JSON，则作为纯文本消息处理
            message = {
              type: 'text',
              content: event.data
            };
          }
          
          console.log('Received WebSocket message:', message);
          
          // 检查是否是心跳响应
          if (message.type === 'pong' || message.type === 'heartbeat') {
            this.lastHeartbeatTime = Date.now();
            console.log('Received heartbeat response from server');
          } else {
            // 处理消息
            this.messageHandlers.forEach(handler => {
              try {
                handler(message);
              } catch (error) {
                console.error('Error in message handler:', error);
              }
            });
          }
        } catch (error) {
          console.error('Error processing WebSocket message:', error);
        }
      };

      this.ws.onclose = (event) => {
        console.log('WebSocket连接关闭', event.code, event.reason);
        this.isConnecting = false;
        this.stopHeartbeat();
        this.reconnect();
      };

      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
        this.isConnecting = false;
        this.stopHeartbeat();
        this.reconnect();
      };
    } catch (error) {
      console.error('Error creating WebSocket connection:', error);
      this.isConnecting = false;
      this.reconnect();
    }
  }

  // 开始发送心跳
  startHeartbeat() {
    this.stopHeartbeat(); // 先停止可能存在的旧定时器
    
    // 发送心跳
    const sendHeartbeat = () => {
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        try {
          const heartbeatMsg = {
            type: 'heartbeat',
            timestamp: Date.now(),
            data: {
              userId: this.getUserIdFromToken(this.lastToken),
              siteId: this.lastSiteId,
              token: this.lastToken
            }
          };
          this.ws.send(JSON.stringify(heartbeatMsg));
          console.log('Sent heartbeat to server:', heartbeatMsg);
        } catch (error) {
          console.error('Error sending heartbeat:', error);
          this.reconnect();
        }
      }
    };

    // 检查心跳响应
    const checkHeartbeat = () => {
      if (this.lastHeartbeatTime && Date.now() - this.lastHeartbeatTime > this.heartbeatTimeout) {
        console.log('Heartbeat timeout, reconnecting...');
        this.reconnect();
      }
    };

    // 立即发送第一个心跳
    sendHeartbeat();
    
    // 设置定时器
    this.heartbeatTimer = setInterval(() => {
      sendHeartbeat();
      checkHeartbeat();
    }, this.heartbeatInterval);
  }

  // 停止发送心跳
  stopHeartbeat() {
    if (this.heartbeatTimer) {
      clearInterval(this.heartbeatTimer);
      this.heartbeatTimer = null;
    }
  }

  reconnect() {
    if (this.reconnectCount >= this.maxReconnectCount) {
      console.error('WebSocket重连次数超过限制');
      return;
    }

    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }

    const delay = Math.min(1000 * Math.pow(2, this.reconnectCount), 30000); // 指数退避
    console.log(`Attempting to reconnect in ${delay}ms (attempt ${this.reconnectCount + 1}/${this.maxReconnectCount})`);

    this.reconnectTimer = setTimeout(() => {
      this.reconnectCount++;
      if (this.lastToken) {
        this.connect(this.lastToken, this.lastSiteId);
      }
    }, delay);
  }

  addMessageHandler(handler) {
    this.messageHandlers.add(handler);
  }

  removeMessageHandler(handler) {
    this.messageHandlers.delete(handler);
  }

  getUserIdFromToken(token) {
    try {
      // 解析JWT token
      const base64Url = token.split('.')[1];
      const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
      const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
      }).join(''));

      const payload = JSON.parse(jsonPayload);
      console.log('Token payload:', payload);
      
      // 从payload中获取用户ID
      return payload.id || null;
    } catch (error) {
      console.error('解析token失败:', error);
      return null;
    }
  }

  close() {
    if (this.ws) {
      this.ws.close();
    }
    if (this.reconnectTimer) {
      clearTimeout(this.reconnectTimer);
    }
    this.stopHeartbeat();
    this.isConnecting = false;
  }
}

export const webSocketClient = new WebSocketClient(); 